<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="编号" prop="code" v-show="false">
        <el-input v-model="queryParams.code" placeholder="编号" clearable @keyup.enter.native="handleQuery()" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['secure:consumeOut:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['secure:consumeOut:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="printBox"
          v-hasPermi="['secure:consumeOut:print']">打印</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table @selection-change="handleSelectionChange" fit v-loading="loading" border :data="dataList">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column min-width="150" label="名称" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-link @click="handleDetail(scope.row)" type="primary">{{
            scope.row.name
          }}</el-link>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="入库序号" min-width="150" prop="joinCode" />
      <el-table-column show-overflow-tooltip min-width="150" label="出库日期" prop="outDate" />
      <el-table-column :show-overflow-tooltip="true" min-width="120" label="部门" prop="dept">
      </el-table-column>
      <!-- <el-table-column
        show-overflow-tooltip
        label="技术指标"
        min-width="150"
        prop="tecTarget"
      /> -->
      
      <el-table-column show-overflow-tooltip min-width="150" label="领用数量" prop="num" />
      <el-table-column show-overflow-tooltip min-width="150" label="当前库存" prop="currentNum" />
      <el-table-column show-overflow-tooltip label="单位" width="150" prop="unitLabel" />
      <el-table-column show-overflow-tooltip min-width="150" label="有效期" prop="limitDate" />
      <el-table-column show-overflow-tooltip min-width="150" label="剩余库存" prop="currentNum">
        <template slot-scope="scope">
          <div>{{ (scope.row.currentNum - scope.row.num).toFixed(2)}}</div>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip min-width="150" label="领用人" prop="user" />
      <el-table-column show-overflow-tooltip min-width="150" label="创建人" prop="createByName" />
      <el-table-column show-overflow-tooltip min-width="150" label="技术要求" prop="directory.techInfo" />
      <el-table-column show-overflow-tooltip min-width="150" label="主要用途" prop="directory.useInfo" />
      <el-table-column show-overflow-tooltip label="规格" width="150" prop="spec" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" v-print="print" icon="el-icon-view"
            v-hasPermi="['secure:consumeOut:printArea']" @click="handleprintArea(scope.row)">打印小票</el-button>
          <el-button size="mini" type="text" icon="el-icon-view" v-hasPermi="['secure:consumeOut:info']"
            @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 打印模板位置 -->

    <PrintBox :checkNum="8" :printRow="printList" :checkLabel="'contentList'" :isVertical="false" id="printBox"
      :isPageSize="false">
      <template slot="title" slot-scope="scope">
        <div>化学试剂药品出库记录表 STET/B/07-02</div>
      </template>
      <!-- <template slot-scope="scope">
       
      </template> -->

      <template slot-scope="scope">
        <div>
          <div style="display: flex;">名称：{{  printList[0].contentList[0] &&  printList[0].contentList[0].name }}</div>
          <div style="display: flex;align-items: center;justify-content: space-between;margin-top: 20px;">
            <div>检测单位名称：苏州交通工程试验检测中心有限公司</div>
            <div style="padding-right: 150px;">索引：{{  printList[0].contentList[0] &&  printList[0].contentList[0].directory.code }}</div>
          </div>
        </div>
        <table style="border-collapse: collapse; table-layout: fixed" border="1" cellspacing="0" class="table-page">
          <tr style="height: 5mm">
            <td style="width: 50mm">入库序号</td>
            <td style="width: 30mm">入库量</td>
            <td style="width: 50mm">日期</td>
            <td style="width: 30mm">出库量</td>
            <td style="width: 40mm">领用人</td>
            <td style="width: 40mm">保管人</td>
            <td style="width: 30mm">累计出库量</td>
          </tr>
          <tr v-for="(e, i) in 15">
            <td>{{  printList[0].contentList[i] &&  printList[0].contentList[i].joinCode }}</td>
            <td>{{  printList[0].contentList[i] && printList[0].contentList[i].inNum }} {{  printList[0].contentList[i] &&  printList[0].contentList[i].unitLabel }}</td>
            <td>{{  printList[0].contentList[i] &&  printList[0].contentList[i].outDate }}</td>
            <td>{{  printList[0].contentList[i] &&  printList[0].contentList[i].num }} {{  printList[0].contentList[i] && printList[0].contentList[i].unitLabel }}</td>
            <td>{{  printList[0].contentList[i] &&  printList[0].contentList[i].user }}</td>
            <td>{{  printList[0].contentList[i] &&  printList[0].contentList[i].managerUser }}</td>
            <td>{{  printList[0].contentList[i] &&  printList[0].contentList[i].totalOutNum }}{{  printList[0].contentList[i] &&  printList[0].contentList[i].unitLabel }}</td>
          </tr>
        </table>
        <div class="page-bottom" style="page-break-after: always">
          <div class="desc">注：本表格自2021年6月1日起生效</div>
        </div>
      </template>
    </PrintBox>
    <!-- 小票打印 -->
    <div id="printArea" class="noprint">
      <div class="printWait">
        <div style="width: 76%;">
          <div class="item">
            <span>名称：</span>
            <span>{{ printItem.name || '' }}</span>
          </div>
          <div class="item">
            <span>编号：</span>
            <span>{{printItem.directory ? printItem.directory.code : '' || ''}}</span>
          </div>
          <div class="item">
            <span>入库序号：</span>
            <span>{{ printItem.joinCode || '' }}</span>
          </div>
          <div class="item">
            <span>有效期：</span>
            <span>{{ printItem.limitDate || '' }}</span>
          </div>
          <div class="item">
            <span>技术要求：</span>
            <span>{{ printItem.directory ? printItem.directory.techInfo : '' || '' }}</span>
          </div>
          <div class="item">
            <span>CAS号：</span>
            <span>{{ printItem.cas || '' }}</span>
          </div>
          <div class="item">
            <span >存放位置：</span>
            <span>{{ printItem.tecTarget || '' }}</span>
          </div>
        </div>
        <div style="text-align: center;width: 24%;">
          <vue-qr :text="textUrl" :size="130"></vue-qr>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  listconsume_out,
  delconsume_out,
  effectgoodsDirectory,
} from "@/api/quality/goods/consumeOut.js";
import printStyle from "@/utils/print.js";
export default {
  name: "consumeOut",
  data() {
    return {
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      dataList: [],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        chemicals: 1
      },
      // 日期范围
      dateRange: [],
      printList: [],
      infos: {},
      userList: [],
      deptOptions: [],
      print: {
        id: 'printArea',
        popTitle: '打印', // 打印配置页上方标题
        extraHead: '', //最上方的头部文字，附加在head标签上的额外标签,使用逗号分隔
        preview: false, // 是否启动预览模式，默认是false（开启预览模式，可以先预览后打印）
        previewTitle: '', // 打印预览的标题（开启预览模式后出现）,
        previewPrintBtnLabel: '', // 打印预览的标题的下方按钮文本，点击可进入打印（开启预览模式后出现）
        zIndex: '', // 预览的窗口的z-index，默认是 20002（此值要高一些，这涉及到预览模式是否显示在最上面）   
        url: '',
        standard: '',
        extraCss: '',
      },
      textUrl:'',
      printItem:{}
    };
  },
  created() {
    const str = sessionStorage.getItem('queryParams');
    if (str) {
      this.queryParams = JSON.parse(str);
      setTimeout(() => {
        sessionStorage.removeItem('queryParams');
      }, 500)
    }
    this.getList();
    this.getDeptTree();
  },
  methods: {
    handleStatusChange(row) {
      let text = row.effectStatus === "1" ? "启用" : "禁用";
      this.$modal
        .confirm('确认要"' + text + '""' + row.name + '"目录吗？')
        .then(function () {
          return effectgoodsDirectory(row.consumeGoodsOutId, row.effectStatus);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.effectStatus = row.effectStatus === "0" ? "1" : "0";
        });
    },
    printBox() {
      //infos  勾选的数据 如果有勾选就打印勾选。
      // if (this.infos.length) {
      //   this.printList = this.infos;
      // } else {
      //   //反之打印当前整个列表
      //   this.printList = this.dataList;
      // }
      console.log();
      console.log(this.infos);
      if (this.infos.length == 0) {
        this.printList = [{
          contentList: this.dataList,
        }]

      } else if (this.infos.length == 1) {
        console.log(this.infos);
        listconsume_out({ joinIndex: this.infos[0].directory.code,pageNum:1,pageSize:300 }).then((response) => {
          this.printList = [{
            contentList: response.rows,
          }];
          console.log(this.printList);
        });
      } else {
        console.log('多数据',this.infos[i]);
        var find = false;
        for (var i = 0; i < this.infos.length; i++) {
          for (var j = i + 1; j < this.infos.length; j++) {
            if (this.infos[i].joinIndex != this.infos[j].joinIndex || this.infos[i].name != this.infos[j].name) {
              // find = true
              this.$message.error('请选择相同索引的化学物质！')
              return
            } else {
              find = true
            }
          }
          console.log(find);
        }
        if (find) {
          this.printList = [{
            contentList: this.infos,
          }]
        } else {
          this.$message.error('请选择相同标准物质！')
          return
        }
      }
      console.log(process.env.VUE_APP_TITLE);
      setTimeout(() => {
        document.title = "标准物质出库记录表 STET/B/21-2";

        this.$print({
          printable: "printBox", //打印区域id
          type: "html", //打印类型是html
          scanStyles: false,
          targetStyles: ["*"],
          style: this.workStyle(),
          onPrintDialogClose: () => {
            document.title = process.env.VUE_APP_TITLE;
          },
        });
      }, 500);
    },
    handleprintArea(e) {
    console.log(e,'/e');
      this.printItem = e
      this.textUrl = process.env.VUE_APP_CODE_API + "consumeOutDetail?id=" + e.consumeGoodsOutId + '&index=' +2;
      console.log(this.textUrl);
      this.$print({
        // 指定要打印的组件名称
        printable: 'printArea',
        id: 'printArea',
        popTitle: "标准物质出库标签", // 打印的标题
        extraCss: "", // 打印可引入外部的一个 css 文件
        extraHead: "", // 打印头部文字
        filter: ['.no-print'],
        // 可选参数，可以设置打印前回调函数和打印后回调函数
        beforePrint: () => { },
        afterPrint: () => { }
      });
    },
    // 可以自定义样式  printStyle 是公共样式 切勿私自修改
    workStyle() {
      return `${printStyle}
        table,
        table tr th,
        table tr td {
          height:17mm;
          padding: 0px;
          font-size: 12px;
        }
        .desc{
        text-align: left; font-size: 12px; margin-top: 10px
      }
            .df {
                display: flex;
              }
      `;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.consumeGoodsOutId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
      this.infos = selection;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      sessionStorage.setItem('queryParams', JSON.stringify(this.queryParams));
      const configId = row.consumeGoodsOutId || this.ids;
      this.$router.push("./addConsumeOut?isEdit=true&id=" + configId);
    },
    handleDetail(row) {
      sessionStorage.setItem('queryParams', JSON.stringify(this.queryParams));
      this.$router.push(
        "./addConsumeOut?isInfo=true&id=" + row.consumeGoodsOutId
      );
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const configId = row.consumeGoodsOutId || this.ids;

      this.$modal
        .confirm('是否确认删除ID为"' + configId + '"的数据项？')
        .then(function () {
          return delconsume_out(configId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    handleAdd() {
      this.$router.push("./addConsumeOut");
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listconsume_out({
        ...this.addDateRangeTime(
          this.queryParams,
          this.dateRange,
          "startEndDate",
          "endEndDate"
        ),
      }).then((response) => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleExport() {
      this.queryParams.ids =this.ids.toString()
      this.download(
        "system/consume_out/export",
        {
          ...this.queryParams,
        },
        `化学品出库表_${this.parseTime(
          new Date().getTime(),
          "{y}-{m}-{d}"
        )}.xlsx`
      );
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
  },
};
</script>
<style>
@media print {
  .noprint {
    display: block !important;
  }
}

@page {
  size: auto;
  margin: 0mm;
}

.procedure {
  word-wrap: break-word;
}
</style>
<style lang="scss" scoped>
.noprint {
  display: none;
}

#printArea {
  width: 200px;
  height: 60px;
  // margin: 10px auto;
  .printWait {
    padding: 5px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    // border: 1px solid #333;
    .item {
      margin-bottom: 2px;
      font-size: 12px;
    }
  }
}
::v-deep .el-dialog__body {
  img {
    width: 100%;
  }
}
</style>
